package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("UrlRestController")
public class UrlRestController extends CmiEmaController {

	/**
	 * Create a new Url entity
	 * 
	 */
	@RequestMapping(value = "/newUrl", method = RequestMethod.POST)
	@ResponseBody
	public Object newUrl(@RequestBody Url url) {
		urlService.saveUrl(url);
		return JSONObject.parse(cmiPsonService.toJsonString(urlDAO.findUrlByPrimaryKey(url.getId()), 2));
	}

	@RequestMapping(value = "/restNewUrl", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewUrl(@RequestBody String urlJson) {
		Url url = new Gson().fromJson(urlJson, Url.class);
		appendReferences(url);
		urlService.saveUrl(url);
		return JSONObject.parse(cmiPsonService.toJsonString(urlDAO.findUrlByPrimaryKey(url.getId()), 2));
	}

	@RequestMapping(value = "/saveUrl", method = RequestMethod.PUT)
	@ResponseBody
	public Url saveUrl(@RequestBody Url url) {
		urlService.saveUrl(url);
		return urlDAO.findUrlByPrimaryKey(url.getId());
	}

	@RequestMapping(value = "/restSaveUrl", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveUrl(@RequestBody String urlJson) {
		Url url = new Gson().fromJson(urlJson, Url.class);
		appendReferences(url);
		CmiPsonService cmiPsonService = new CmiPsonService();
		urlService.saveUrl(url);
		return JSONObject.parse(cmiPsonService.toJsonString(urlDAO.findUrlByPrimaryKey(url.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteUrl/{urlId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteUrl(@PathVariable Integer urlId) {
		Url url = urlDAO.findUrlByPrimaryKey(urlId);
		urlService.deleteUrl(url);
	}

	@RequestMapping(value = "/restConfirmDeleteUrls")
	@ResponseBody
	public Object restConfirmDeleteUrls(@RequestBody Set<Integer> deleteUrlsIds) {
		Set<Url> deleteUrls = urlDAO.findUrlsByIds(deleteUrlsIds);
		Set<Url> referencedUrls = urlService.loadReferenceUrls(deleteUrls);
		deleteUrls.removeAll(referencedUrls);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedUrls);
		jsonObject.put("deleteEntitys", deleteUrls);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteUrls")
	@ResponseBody
	public Object restDeleteUrls(@RequestBody Set<Url> deleteUrls) {
		Iterator<Url> iterator = deleteUrls.iterator();
		while (iterator.hasNext()) {
			Url currentUrl = iterator.next();
			urlService.deleteUrl(currentUrl);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listUrls");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadUrl/{urlId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadUrl(@PathVariable Integer urlId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(urlDAO.findUrlByPrimaryKey(urlId), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadUrlSite/{urlId}/site", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadUrlSite(@PathVariable Integer urlId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(urlDAO.findUrlByPrimaryKey(urlId).getSite(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadUrlUser/{urlId}/user", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadUrlUser(@PathVariable Integer urlId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(urlDAO.findUrlByPrimaryKey(urlId).getAuthor(), 2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	@RequestMapping(value = "/restLoadUrlCrawlerfiles/{urlId}/crawlerfiles/{relatedcrawlerfileId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadUrlCrawlerfiles(@PathVariable Integer urlId, @PathVariable Integer relatedcrawlerfileId,
			@RequestBody CmiPagination cmiPagination) {
		Crawlerfile crawlerfile = crawlerfileDAO.findCrawlerfileByPrimaryKey(relatedcrawlerfileId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(crawlerfile, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadUrlCrawlerknowledges/{urlId}/crawlerknowledges/{relatedcrawlerknowledgeId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadUrlCrawlerknowledges(@PathVariable Integer urlId,
			@PathVariable Integer relatedcrawlerknowledgeId, @RequestBody CmiPagination cmiPagination) {
		Crawlerknowledge crawlerknowledge = crawlerknowledgeDAO
				.findCrawlerknowledgeByPrimaryKey(relatedcrawlerknowledgeId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(crawlerknowledge, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadUrlEvents/{urlId}/events/{relatedeventId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadUrlEvents(@PathVariable Integer urlId, @PathVariable Integer relatedeventId,
			@RequestBody CmiPagination cmiPagination) {
		Event event = eventDAO.findEventByPrimaryKey(relatedeventId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(event, 2, cmiPagination));
	}

	public void appendReferences(Url url) {

		Site site = url.getSite();
		if (site != null)
			url.setSite(siteService.findSiteByPrimaryKey(site.getId()));

		User author = url.getAuthor();
		if (author != null)
			url.setAuthor(userService.findUserByPrimaryKey(author.getId()));

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Crawlerfile> crawlerfilesForUrl = new HashSet<>();
		for (Crawlerfile crawlerfile_Url : url.getCrawlerfilesForUrl()) {
			crawlerfilesForUrl.add(crawlerfileService.findCrawlerfileByPrimaryKey(crawlerfile_Url.getId()));
		}
		url.setCrawlerfilesForUrl(crawlerfilesForUrl);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Crawlerknowledge> crawlerknowledgesForUrl = new HashSet<>();
		for (Crawlerknowledge crawlerknowledge_Url : url.getCrawlerknowledgesForUrl()) {
			crawlerknowledgesForUrl
					.add(crawlerknowledgeService.findCrawlerknowledgeByPrimaryKey(crawlerknowledge_Url.getId()));
		}
		url.setCrawlerknowledgesForUrl(crawlerknowledgesForUrl);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Event> eventsForUrl = new HashSet<>();
		for (Event event_Url : url.getEventsForUrl()) {
			eventsForUrl.add(eventService.findEventByPrimaryKey(event_Url.getId()));
		}
		url.setEventsForUrl(eventsForUrl);
	}

	@RequestMapping(value = "/restGetUrlSite/{urlId}/site", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetUrlSite(@PathVariable Integer urlId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(urlDAO.findUrlByPrimaryKey(urlId).getSite(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetUrlUser/{urlId}/user", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetUrlUser(@PathVariable Integer urlId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(urlDAO.findUrlByPrimaryKey(urlId).getAuthor(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetUrlCrawlerfiles/{urlId}/crawlerfiles", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetUrlCrawlerfiles(@PathVariable Integer urlId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(urlDAO.findUrlByPrimaryKey(urlId).getCrawlerfilesForUrl(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetUrlCrawlerknowledges/{urlId}/crawlerknowledges", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetUrlCrawlerknowledges(@PathVariable Integer urlId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(urlDAO.findUrlByPrimaryKey(urlId).getCrawlerknowledgesForUrl(), 2,
				cmiPagination));
	}

	@RequestMapping(value = "/restGetUrlEvents/{urlId}/events", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetUrlEvents(@PathVariable Integer urlId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(urlDAO.findUrlByPrimaryKey(urlId).getEventsForUrl(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restListUrls", method = RequestMethod.GET)
	@ResponseBody
	public Object restListUrls() {
		return JSONObject.parse(cmiPsonService.toJsonString(urlService.loadUrls(), 2));
	}

	@RequestMapping(value = "/restListUrlsPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListUrlsPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = urlPaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Url> urls = urlDAO.findAllUrls(startResult, cmiPagination.getPaginationSize());
		String urlString = cmiPsonService.toPsonString(urls, 2, cmiPagination);

		return JSONObject.parse(urlString);
	}

	@RequestMapping("/urlSelectBox")
	@ResponseBody
	public JSONObject urlSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键
			case "Site":
				entitySet = siteService.loadSitesByIdSet(searchValue);
				break;
			case "User":
				entitySet = userService.loadUsersByIdSet(searchValue);
				break;

			// 被引用键
			case "Crawlerfile":
				entitySet = crawlerfileService.loadCrawlerfilesByIdSet(searchValue);
				break;
			case "Crawlerknowledge":
				entitySet = crawlerknowledgeService.loadCrawlerknowledgesByIdSet(searchValue);
				break;
			case "Event":
				entitySet = eventService.loadEventsByIdSet(searchValue);
				break;
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键
			case "Site":
				entitySet = siteDAO.findAllSites((pageNumber - 1) * paginationSize, paginationSize);
				count = siteService.countSites();
				break;
			case "User":
				entitySet = userDAO.findAllUsers((pageNumber - 1) * paginationSize, paginationSize);
				count = userService.countUsers();
				break;

			// 被引用键
			case "Crawlerfile":
				entitySet = crawlerfileDAO.findAllCrawlerfiles((pageNumber - 1) * paginationSize, paginationSize);
				count = crawlerfileService.countCrawlerfiles();
				break;
			case "Crawlerknowledge":
				entitySet = crawlerknowledgeDAO.findAllCrawlerknowledges((pageNumber - 1) * paginationSize,
						paginationSize);
				count = crawlerknowledgeService.countCrawlerknowledges();
				break;
			case "Event":
				entitySet = eventDAO.findAllEvents((pageNumber - 1) * paginationSize, paginationSize);
				count = eventService.countEvents();
				break;
			}
		} else {
			switch (selectItem) {
			// 外键
			case "Site":
				entitySet = siteDAO.findSiteByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = siteService.countSitesByName(queryword);
				break;
			case "User":
				entitySet = userDAO.findUserByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = userService.countUsersByName(queryword);
				break;

			// 被引用键
			case "Crawlerfile":
				entitySet = crawlerfileDAO.findCrawlerfileByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = crawlerfileService.countCrawlerfilesByName(queryword);
				break;
			case "Crawlerknowledge":
				entitySet = crawlerknowledgeDAO.findCrawlerknowledgeByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = crawlerknowledgeService.countCrawlerknowledgesByName(queryword);
				break;
			case "Event":
				entitySet = eventDAO.findEventByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = eventService.countEventsByName(queryword);
				break;
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
